// pages/propagateAdmin/index.ts
import {employRecord, pageRecord} from "../../service/api/api-propagate";
import {fontSizeCalc, handleCode, handleErrCode} from "../../utils/util";
const rules = [{
    name: "reward",
    rule: ["required","isAmount","range:[0.01,100]"],
    msg: ["积分不能为空","请输入数字，保留两位小数","范围0.01-100"]
}]

let toast;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchText: "",// 搜索关键字
        currentTab: 0, // 当前选中的tab
        scrollTop: 0, // 滚动到顶部
        tabs: [
            {name: "未收录"},
            {name: "已收录"},
        ],// 筛选条件
        recordList: [],// 纪录列表
        backRecordList: [],// 纪录列表，本地过滤用
        access: {} as any,// 当前用户权限
        currentUser: {},// 当前用户信息
        options: '',
        modal: false,// 是否显示弹窗
        modalReward: '',// 弹窗输入的积分
        curRecord: {},// 当前编辑的纪录
        triggered: false,// 自定义下拉是否被触发 true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
        searchTimeout: null,
        current: 1,// 第几页
        pageSize: 20,// 每页多少条数据
        total: 0,// 总共有多少条

        iconSize: fontSizeCalc(40),
        tabFontSize: fontSizeCalc(28),
        labelSize: fontSizeCalc(28),
        inputSize: fontSizeCalc(32),
        btnHeight: fontSizeCalc(60) + 'rpx',
        btnLineHeight: fontSizeCalc(36) + 'rpx',
        opLabelSize: fontSizeCalc(24),
        opBtnWidth: fontSizeCalc(140) + 'rpx',
        opBtnHeight: fontSizeCalc(50) + 'rpx',
        opBtnLineHeight: fontSizeCalc(20) + 'rpx',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const {globalData: {access, currentUser}} = getApp();
        this.setData({
            access,
            currentUser,
            options: JSON.stringify(options)
        })
        this.tabsChange({detail: {index: this.data.currentTab}});
    },
    /**
     * 开始搜索
     * @param detail
     * @param showLoading
     * @param current 分页数据，
     */
    async searchFun({detail = {value: ''},current = 1}) {
        // 有传值的时候才把这个值设置进去
        let _that = this;
        let {pageSize,currentTab} = this.data;
        // if (_that.isEnd()){
        //     return
        // }
        _that.setData({
            current: current,
            searchText: detail.value
        })
        wx.showLoading({
            title: '搜索中...'
        })
        // 执行搜索函数
        await pageRecord({
            current,
            pageSize,
            title: detail.value,
            isEmploy: currentTab
        }).then(async (response) => {
            _that.handleListData(response)
        }).catch(error => {
            console.warn(error)
            handleCode(error, 'none')
        }).finally(() => {
            // 标题栏隐藏刷新转圈圈图标
            _that.searchFinally()
        })
    },
    /**
     * 搜索取消
     */
    searchCancel() {
        console.log('chCancel');
        this.setData({
            searchText: ""
        })
        this.searchFun({})
    },
    /**
     * 切换tab
     * @param detail
     */
    tabsChange({detail = {index: 0}}) {
        this.setData({
            currentTab: detail.index,
            scrollTop: 0,
            current: 1,
            total: 0,
            searchText: ""
        })
        this.searchFun({});// 开始搜索

        // 先做本地过滤
        // let currentTab = detail.index;
        // let {backRecordList} = this.data;
        // this.setData({
        //     recordList: backRecordList.filter(item =>{
        //         if (detail.index === 0){// 未收录
        //             return item.isEmploy !== 1;
        //         } else {
        //             return item.isEmploy === 1; // 已收录
        //         }
        //     }),
        //     currentTab,
        //     scrollTop: 0
        // })
    },

    /**
     * 处理返回的列表值
     * @param res
     */
    handleListData(res: Object) {
        let dataList = [], total = this.data.total;
        if (res?.code === 0 && res?.data?.data) {
            const newData = res.data.data || [];
            dataList = Array.isArray(newData) && newData.map((item, index) => {
                const {typeName, bgColor} = this.handleRecordType(item)
                item.publishTime = item.publishTime.split(' ')[0]
                return {
                    ...item,
                    bgColor,
                    typeName
                }
            }) || [];
            total = res.data.total || 0
        } else {
            handleErrCode(res)
        }
        const oldList = this.data.recordList
        if (this.data.current > 1){// 上拉加载更多
            dataList = [...oldList, ...dataList]
        }
        this.setData({
            recordList: dataList,
            total
            // backRecordList: dataList
        })
        // 主动触发一次
        // this.tabsChange({detail: {index: this.data.currentTab}})
    },

    /**
     * 处理一下纪录状态
     * @param data
     */
    handleRecordType({isEmploy}) {
        return {
            typeName: isEmploy === 1 ? '已收录' : '未收录',
            bgColor: isEmploy === 1 ? '#389E0D' : '#F5A34D',
        }
    },
    /**
     * 跳转到详情
     */
    gotoDetail(e: any) {
        const record = e.currentTarget.dataset.item || {};
        wx.navigateTo({
            url: '/pages/propagateDetail/index?isAdmin=true&&id=' + record.id,
        })
    },

    /**
     * 显示弹窗弹窗
     */
    showModal(e:any){
        const record = e.currentTarget.dataset.item || {};
        this.setData({
            modal: true,
            curRecord: record,
            modalReward: record.reward,
        })
    },

    /**
     * 关闭弹窗弹窗
     */
    modalCancel(){
        this.setData({
            modal: false,
            modalReward: '',
        })
    },

    /**
     * 收录确认弹窗
     */
    modalConfirmFun(){
        const {curRecord,modalReward} = this.data || {}
        let formData = {
            reward: modalReward
        };
        this.selectComponent("#form").validate(formData, rules).then(res => {
            this.employFun({...formData, id: curRecord.id || 0})
        }).catch(errors => {
            console.log(errors)
        })
    },

    /**
     * 收录确认弹窗
     */
    async employFun(params) {
        wx.showLoading({
            title: '请稍后...'
        })
        // 执行搜索函数
        await employRecord(params).then(async (res) => {
            if (res?.code === 0) {
                handleCode(res, '收录成功');
                setTimeout(() => {
                    this.searchFun({});// 开始搜索
                }, 1000)
            } else {
                handleErrCode()
            }
            wx.hideLoading();
            this.modalCancel();
        }).catch(error => {
            handleErrCode(error, 'none')
            wx.hideLoading();
            this.modalCancel();
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 提示语
     */
    showToast(title){
        let params = {
            title,
        }
        toast && toast.show(params);
    },

    /**
     * 是否到底的判断
     */
    isEnd(){
        let {current,pageSize,total} = this.data;
        if (total && current !== 1 && current * pageSize >= total){
            this.showToast('已经到底了')
            return true
        } else {
            return false
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        toast = this.selectComponent("#toast")
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // this.tabsChange({detail: {index: this.data.currentTab}});
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // wx.reLaunch({
        //     url:'/pages/home/index'
        // })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * scroll-view 下拉刷新
     */
    refresherPulling(){
        this.setData({
            triggered: true
        })
    },

    /**
     * 刷新函数
     */
    refreshFun(e:object, current = 1){
        // 标题栏显示刷新图标，转圈圈
        wx.showNavigationBarLoading()

        this.searchFun({current});
        clearTimeout(this.data.searchTimeout);
        let searchTimeout = setTimeout(() => {
            this.searchFinally()
        }, 2000);
        this.setData({
            searchTimeout,
        })
    },

    /**
     * 下拉加载更多数据函数
     */
    scrollToLowerFun(){
        if (this.isEnd()){
            return
        }
        // 调用刷新函数
        this.refreshFun({},this.data.current + 1)
    },

    /**
     * 搜索最终
     */
    searchFinally(){
        clearTimeout(this.data.searchTimeout)
        // 标题栏隐藏刷新转圈圈图标
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        wx.hideLoading();
        this.setData({
            triggered: false
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    taskExecuteShareFun() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    }
})